/**
 * Created by chenyong on 2015/7/16.
 */

var request = require('request');
var _apiToken = null;


var _getApiToken = function(){
    var oauth = {
        grant_type:'client_credentials',
        client_id:'7d21c0f1-78b8-4078-a8cc-89726b228e4d',
        client_secret:'fGus4O82u8fBsVinWXPQBFR/XHEX8cco/HCf/khR8w0=',
        resource:'http://srv.bigpixel.cn'
    };
    var token_endpoint = 'https://login.chinacloudapi.cn/a76b6aab-8a67-41fd-87f2-23c2a087d961/oauth2/token?api-version=1.0';
    request.post({url:token_endpoint, form: oauth}, function(err,httpResponse,body){
        if(!err)
        {
            var _body=JSON.parse(body);
            var _token=_body.access_token;
            if(_token!=null){
                _apiToken = JSON.parse(body);
                var delayTime = (parseInt(_apiToken.expires_in) - 100)*1000;
                setTimeout(_getApiToken,delayTime);
                console.log(body);
            }else{
                //未返回access_token
                console.log(body);
                _getApiToken();
            }
        }
        else
        {
            //跟踪err
            console.log(err);
            _getApiToken();
        }
    })
};

_getApiToken();

var _getcachedToken = function(){
    return _apiToken.access_token;
};

exports.getcachedToken = _getcachedToken;